/*
 * Created on 2005-8-19
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.jedi;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import com.tss.util.DbConn;
import com.tss.util.DbRs;
import com.tss.util.ParamUtils;
import com.tss.util.TSSDate;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class User extends BaseObj {
	public User() {}
	public User(String id) { this.userId = id;}
	
	public void delete() { 
		clearErr();
		DbConn conn = new DbConn();
		try {
			String sql = "";
			DbRs rs = null;
			sql = "select * from t_message_board where author_id = ?";
			conn.prepare(sql);
			conn.setString(1,getId());
			rs = conn.executeQuery();
			if (rs != null && rs.size() > 0) {
				setErr("����");
				return;
			}
			sql = "delete from userinfo where user_id = ?";
			conn.prepare(sql);
			conn.setString(1,getId());
			conn.executeUpdate();
		}
		catch(Exception ex) {
			ex.printStackTrace();
			setErr(ex.getMessage());
		}
		finally {
			conn.close();
		}
	}
	
	public void updatePwd(String pwd_old,String pwd_new) {
		clearErr();
		DbConn conn = new DbConn();
		try {
			String sql = "";
			sql = "select * from userinfo where user_id = ?";
			conn.prepare(sql);
			conn.setString(1,getId());
			DbRs rs = conn.executeQuery();
			if (rs == null || rs.size() == 0) {
				setErr("此用户不存在！");
				return;
			}
			String pwd = get(rs,0,"pwd");
			if (!pwd.trim().equalsIgnoreCase(pwd_old)) {
				setErr("两次输入的密码不一致！");
				return;
			}
			sql = "update userinfo set " +
				"pwd = ? where user_id = ?";
			conn.prepare(sql);
			conn.setString(1,pwd_new.trim());
			conn.setString(2,getId());
			conn.executeUpdate();
		}
		catch(Exception ex) {
			ex.printStackTrace();
			setErr(ex.getMessage());
		}
		finally {
			conn.close();
		}
	}
	
	public void update() {
		clearErr();
		DbConn conn = new DbConn();
		try {
			conn.setAutoCommit(false);
			String sql = "";
			sql = "update userinfo set " +
				"user_name = ?,email = ?,phone = ?,mobile = ?," +
				"city = ?,head_img = ?,role_id = ? where user_id = ?";
			conn.prepare(sql);
			conn.setString(1,getUserName());
			conn.setString(2,getEmail());
			conn.setString(3,getPhone());
			conn.setString(4,getMobile());
			conn.setString(5,getCity());
			conn.setString(6,getHeadImg());
			conn.setString(7,getRoleId());
			conn.setString(8,getId());
			conn.executeUpdate();
			
			sql = "delete from userrole where user_id = ?";
			conn.prepare(sql);
			conn.setString(1,getId());
			conn.executeUpdate();
			
			String mroles=getURole().getRole_id();
			mroles=mroles.substring(0,mroles.length()-1);
			String [] mroles_str=mroles.split(",");
			for(int j=0;j<mroles_str.length;j++){
				Userrole uRole=new Userrole();
				uRole.setUser_id(getId());
				uRole.setRole_id(mroles_str[j]);
				insertUrole(conn,uRole);
				
			}
			conn.commit();
		}
		catch(Exception ex) {
			ex.printStackTrace();
			setErr(ex.getMessage());
		}
		finally {
			conn.close();
		}
	}
	public void modiSelfinfo() {
		clearErr();
		DbConn conn = new DbConn();
		try {
		
			String sql = "";
			sql = "update userinfo set " +
				"user_name = ?,email = ?,phone = ?,mobile = ?," +
				"city = ?,head_img = ? where user_id = ?";
			conn.prepare(sql);
			conn.setString(1,getUserName());
			conn.setString(2,getEmail());
			conn.setString(3,getPhone());
			conn.setString(4,getMobile());
			conn.setString(5,getCity());
			conn.setString(6,getHeadImg());
			conn.setString(7,getId());
			conn.executeUpdate();
		}
		catch(Exception ex) {
			ex.printStackTrace();
			setErr(ex.getMessage());
		}
		finally {
			conn.close();
		}
	}
	
	public void insert() {
		clearErr();
		DbConn conn = new DbConn();
		DbRs rs = null;
		try {
			conn.setAutoCommit(false);
			String sql = "";
			
			sql = "select * from userinfo where user_id = ?";
			conn.prepare(sql);
			conn.setString(1,getId());
			rs = conn.executeQuery();
			if (rs != null && rs.size() > 0) {
				setErr("登陆名称已经存在请使用其它登陆名称");
				return;
			}
			sql = "insert into userinfo(" + 
				"user_id,user_name,pwd,email,phone," + 
				"mobile,city,head_img,role_id,article_num) values (" +
				"?,?,?,?,?," + 
				"?,?,?,?,?)";
			conn.prepare(sql);
			conn.setString(1,getId());
			conn.setString(2,getUserName());
			conn.setString(3,getPwd());
			conn.setString(4,getEmail());
			conn.setString(5,getPhone());
			conn.setString(6,getMobile());
			conn.setString(7,getCity());
			conn.setString(8,getHeadImg());
			conn.setString(9,getRoleId());
			conn.setLong(10,getArticleNum());
			conn.executeUpdate();
			String mroles=getURole().getRole_id();
			String [] mroles_str=mroles.split(",");
			for(int j=0;j<mroles_str.length;j++){
				Userrole uRole=new Userrole();
				uRole.setUser_id(getId());
				uRole.setRole_id(mroles_str[j]);
				insertUrole(conn,uRole);
				
			}
			
			conn.commit();
		}
		catch(Exception ex) {
			ex.printStackTrace();
			setErr(ex.getMessage());
		}
		finally {
			conn.close();
		}
	}
	
	/**
	 * 添加一个用户多个角色
	 *
	 */
	public void insertUrole(DbConn conn,Userrole uRole) throws Exception {
		
		clearErr();
			String sql = "";
			sql = "insert into userrole(user_id,role_id) values (?,?)";
			conn.prepare(sql);
			conn.setString(1,uRole.getUser_id());
			conn.setString(2,uRole.getRole_id());
			conn.executeUpdate();
	}
	public boolean hasPower(String powerId) {
		if (getRole() == null || getRole().getId().trim().equals("")) return false;
		List list = getRole().getPower(); 
		if (list == null || list.size() == 0) return false;
		for(int i=0;i<list.size();i++) {
			Power item = (Power)list.get(i);
			if (item.getId().equals(powerId)) return true;
		}
		return false;
	}
	public void login(HttpSession session,HttpServletRequest request,String userid,String pwd,String suRoleId,String role_id) {
		clearErr();
		DbConn conn = new DbConn();
		DbRs rs = null;
		try {
			String sql = "";
			
			sql = "select user_id from userinfo where role_id = ?";
			conn.prepare(sql);
			conn.setString(1,suRoleId);
			rs = conn.executeQuery();
			if (rs == null || rs.size() == 0) {
				if (userid.trim().equalsIgnoreCase("admin")) {
					if (!pwd.trim().equalsIgnoreCase("admin")) {
						setErr("密码错误");
						return;
					}
					setId("admin");
					setUserName("administrator");
					setInitOperator(true);
					session.setAttribute("LoginUser",this);
					return;
				}
			}
			sql = "select a.*,b.role_name,b.role_desc" +
				" from userinfo a inner join roleinfo b on a.role_id = b.role_id where a.user_id = ?";
			conn.prepare(sql);
			conn.setString(1,userid);
			rs = conn.executeQuery();
			if (rs == null || rs.size() == 0) {
				setErr("用户不存在");
				return;
			}
			String userpwd = get(rs,0,"pwd");
			if (!userpwd.equalsIgnoreCase(pwd)) {
				setErr("密码无效!");
				return;
			}
			setId(userid);
			setUserName(get(rs,0,"user_name"));
			setEmail(get(rs,0,"email"));
			setPhone(get(rs,0,"phone"));
			setMobile(get(rs,0,"mobile"));
			setCity(get(rs,0,"city"));
			setHeadImg(get(rs,0,"head_img"));
			if (role_id.trim().equals("")) {setRoleId(get(rs,0,"role_id"));}
			else {setRoleId(role_id);};
			sql = "select * from roleinfo where role_id=? " ;			
			conn.prepare(sql);
			conn.setString(1,getRoleId());
			rs = conn.executeQuery();
			String RoleName = get(rs,0,"role_name");
			sql = "insert into loginlog (" +
				"user_id,user_name,role_id,role_name,login_addr,login_time" +
				") values (" +
				"?,?,?,?,?,?)";
			conn.prepare(sql);
			conn.setString(1,getId());
			conn.setString(2,getUserName());
			conn.setString(3,getRoleId());
			conn.setString(4,RoleName);
			conn.setString(5,ParamUtils.getRemoteHost(request));
			conn.setString(6,TSSDate.fullTime());
			conn.executeUpdate();
		}
		catch(Exception ex) {
			ex.printStackTrace();
			setErr(ex.getMessage());
			return ;
		}
		finally {
			conn.close();
		}
		//设置角色到session中
		RoleMgr roleMgr = new RoleMgr();
		setRole(roleMgr.get(getRoleId(),true));
		if (roleMgr.hasErr()) {
			setErr(roleMgr.getErr());
			return;
		}
		session.setAttribute("LoginUser",this);
		return;
	}
	
	public void setId(String id) {this.userId = id;}
	public void setUserName(String userName) {this.userName = userName;}
	public void setPwd(String pwd) {this.pwd = pwd;}
	public void setEmail(String email) {this.email = email;}
	public void setPhone(String phone) {this.phone = phone;}
	public void setMobile(String mobile) {this.mobile = mobile;}
	public void setCity(String city) {this.city = city;}
	public void setHeadImg(String headImg) {this.headImg = headImg;}
	public void setRoleId(String id) {this.roleId = id;}
	public void setRole(String roleId) {setRole(roleId,false);}
	public void setRole(String roleId,boolean isGetPower) {
		RoleMgr roleMgr = new RoleMgr();
		this.role = roleMgr.get(roleId,isGetPower);
		if (roleMgr.hasErr()) setErr(roleMgr.getErr());
	}
	public void setRole(Role role) {this.role = role;}
	public void setArticleNum(long articleNum) {this.articleNum = articleNum;}
	public void setInitOperator(boolean isInit) {isInitOperator = isInit;}
	public boolean isSuperAdmin() {return isSuperAdministrator;}
	public String getId() {return userId;}
	public String getUserName() {return userName;} 
	public String getPwd() {return pwd;}
	public String getEmail() {return email;}
	public String getPhone() {return phone;}
	public String getMobile() {return mobile;}
	public String getCity() {return city;}
	public String getCityID(String [] cities) {
		String r = "";
		for(int i=0;i<cities.length;i++) {
			if (cities[i].equals(city)) return i + "";
		}
		return "";
	}
	public String getHeadImg() {return headImg;}
	public String getRoleId() {return roleId;}
	public Role getRole() {return role;}
	public long getArticleNum() {return articleNum;}
	public boolean isInitOperator() {return isInitOperator;}
	public List getRoles() {		return roles;	}
	public void setRoles(List roles) {	this.roles = roles;	}
	private boolean isInitOperator = false;
	private boolean isSuperAdministrator = false;
	private String userId = "";
	private String userName = "";
	private String pwd = "";
	private String email = "";
	private String phone = "";
	private String mobile = "";
	private String city = "";
	private String headImg = "";
	private String roleId = "";
	private Role role = null;
	private List roles = null;
	private long articleNum = 0;
	private Userrole uRole=null;
	public Userrole getURole() {
		return uRole;
	}
	public void setURole(Userrole role) {
		uRole = role;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
}
